import sys,signal,os,json,time,sys
from _thread import start_new_thread

p_server = open('/tmp/server-50000','w')
p_client = ''
auth = 0
def send_msg(msg,fp):
    fp.write( json.dumps( msg ) + '\n' )
    fp.flush()

def recv_msg(fp):
    try:
        msg = fp.readline()
        return json.loads(msg)
    except:
        return None

def msg_poll(fp):
    global auth
    while True:
        msg = recv_msg(p_client)
        if msg is None:
            break
        if msg['type']=='ctrl' and msg['value']=='quit':
            print('server quit')
            fp.close()
            break
        elif msg['type']=='p':
            print('%s 说：%s' %(msg['from'],msg['value']))
        elif msg['type']=='m':
            print('%s 向你发悄悄话：%s'%(msg['from'],msg['value']))
        elif msg['type']=='users':
            print('在线用户有：')
            for u in msg['value']:
                print(u)
        elif msg['type']=='ctrl' and msg['value']=='notExist':
            print('用户不在线')
        elif msg['type']=='ctrl' and msg['value']=='hello':
            auth = msg['auth']
    #exit
    sys.stdin.close()
    
tid = None
def open_handler(signum, frame):
    print('client pipe open')
    
signal.signal(signal.SIGUSR1, open_handler)

if __name__=='__main__':
    user1 = input('称呼:>')
    #print(usr1)
    msg = {'type':'r','from':user1, 'to':'', 'value':os.getpid()}
    send_msg(msg,p_server)
    signal.pause()
    p_name = '/tmp/client-%s' % (50000+os.getpid(), )
    #print('signal pipe: %s'%p_name)
    p_client = open(p_name,'r')
    tid = start_new_thread(msg_poll,(p_client,))
    
    num = 0
    while True:
        try:
            m=input('>')
        except:
            break
        num += 1
        if m=='q':
            msg = {'type':'quit','from':auth,'value':os.getpid()}
            try:
                send_msg(msg,p_server)
                break
            except:
                break
        elif m=='qs':
            msg = {'type':'ctrl','from':auth,'value':'quit'}
        elif m=='users':
            msg = {'type':'ctrl','from':auth,'to':'','value':'users'}
        elif m=='p':
            m1=input('内容:>')
            msg = {'type':'p','from':auth, 'to':'', 'value':'%s'%m1}
        elif m=='m':
            mto = input('who:>')
            m1 = input('内容：>')
            msg = {'type':'m','from':auth, 'to':mto, 'value':'%s'%m1}
        else:
            msg=None
        if msg is not None:
            try:
                send_msg(msg, p_server)
            except:
                break
    try:
        p_server.close()
        p_client.close()
    except:
        pass
    
